package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.DeleteFocusedBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.res_data.RewardByWalletBody;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.fragment.OtherArticleFg;
import com.zlx.sharelive.fragment.OtherGraphicFg;
import com.zlx.sharelive.fragment.OtherLongVideoFg;
import com.zlx.sharelive.fragment.OthersShortVideoFg;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.NullTokenUtils;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * 他人主页
 */
public class OthersHomepageAc extends BaseAc {

    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_id)
    TextView tv_id;
    @BindView(R.id.tv_make)
    TextView tv_make;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_praise)
    TextView tv_praise;
    @BindView(R.id.tv_attention)
    TextView tv_attention;
    @BindView(R.id.tv_fan)
    TextView tv_fan;
    @BindView(R.id.tv_follow_closely)
    TextView tv_follow_closely;
    @BindView(R.id.tv_type1)
    TextView tv_type1;
    @BindView(R.id.tv_type2)
    TextView tv_type2;
    @BindView(R.id.tv_type3)
    TextView tv_type3;
    @BindView(R.id.tv_type4)
    TextView tv_type4;
    @BindView(R.id.view_type1)
    View view_type1;
    @BindView(R.id.view_type2)
    View view_type2;
    @BindView(R.id.view_type3)
    View view_type3;
    @BindView(R.id.view_type4)
    View view_type4;

    private String over;
    private QueryByBean.InfoDTO.ResultDTO mData;
    private String uid;
    private List<BaseFg> mFragment = new ArrayList<>();
    private List<TextView> mTextViewList = new ArrayList<>();
    private List<View> mViewList = new ArrayList<>();
    private String vip;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_others_homepage;
    }

    @Override
    public void initViews() {
        super.initViews();

        vip = (String) SPUtil.get(this, Constants.SP_VIP, "");

        mTextViewList.clear();
        mTextViewList.add(tv_type1);
        mTextViewList.add(tv_type2);
        mTextViewList.add(tv_type3);
        mTextViewList.add(tv_type4);
        mViewList.clear();
        mViewList.add(view_type1);
        mViewList.add(view_type2);
        mViewList.add(view_type3);
        mViewList.add(view_type4);

        uid = getIntent().getStringExtra("uid");
        queryById();
        queryById2();
        initFragment();
    }

    private void queryById2() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this), (String) SPUtil.get(OthersHomepageAc.this, Constants.SP_ID, "")).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
            @Override
            public void onSuccess(ApiResponse<QueryByBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            if (data.getData().getInfo().size() > 0) {
                                if (null != data.getData().getInfo().get(0).getResult()) {
                                    over = data.getData().getInfo().get(0).getResult().getMoney();
                                }
                            }
                        }
                    }
                }
            }
        }));
    }

    private void initFragment() {
        mFragment.clear();
        mFragment.add(OtherLongVideoFg.getInstance(uid));
        mFragment.add(OthersShortVideoFg.getInstance(uid));
        mFragment.add(OtherArticleFg.getInstance(uid));
        mFragment.add(OtherGraphicFg.getInstance(uid));
        commitAllowingStateLoss(0);
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragment.get(position);
            transaction.add(R.id.fl_layout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏所有Fragment
     */
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragment.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this), uid).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
            @Override
            public void onSuccess(ApiResponse<QueryByBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getResult()) {
                                        setData(data.getData().getInfo().get(0).getResult());
                                    }
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    private void setData(QueryByBean.InfoDTO.ResultDTO data) {
        mData = data;
        GlideImgManager.glideLoader(this, data.getAvatar(), iv_head, 0);
        tv_nickname.setText(data.getNickname());
        tv_id.setText("ID:" + data.getId());
        if (!StringUt.isEmpty(data.getMakingType())) {
            tv_make.setText("交友属性:" + data.getMakingType());
        } else {
            tv_make.setText("交友属性:未知");
        }
        tv_content.setText(data.getSignature());
        tv_praise.setText(data.getLike());
        tv_attention.setText(data.getFocusedCount());
        tv_fan.setText(data.getFansCount());
        if (data.getIsAttention().equals("2")) {
            tv_follow_closely.setText("+关注");
        } else {
            tv_follow_closely.setText("已关注");
        }

        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            /**
             * 获取设置用户信息. 通过返回的 userId 来封装生产用户信息.
             * @param userId 用户 ID
             */
            @Override
            public UserInfo getUserInfo(String userId) {
                UserInfo userInfo = new UserInfo(data.getId(), data.getNickname(), Uri.parse(data.getAvatar()));
                return userInfo;
            }

        }, true);
    }

    @OnClick({R.id.iv_back, R.id.ll_type1, R.id.ll_type2, R.id.ll_type3, R.id.ll_type4,
            R.id.ll_private_message, R.id.tv_follow_closely, R.id.ll_reward})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_reward:
                //打赏
                rewardDialog();
                break;
            case R.id.ll_private_message:
                if (!StringUt.isEmpty(vip)) {
                    if (!vip.equals("2")) {
                        if (!StringUt.isEmpty(mData.getId()) && !StringUt.isEmpty(mData.getNickname()) && !StringUt.isEmpty(mData.getAvatar())) {
                            UserInfo userInfo = new UserInfo(mData.getId(), mData.getNickname(), Uri.parse(mData.getAvatar()));
                            RongIM.getInstance().refreshUserInfoCache(userInfo);
                        }
                        Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
                        String targetId = uid;
                        String title = mData.getNickname();
                        Long fixedMsgSentTime = System.currentTimeMillis();
                        RongIM.getInstance().startConversation(OthersHomepageAc.this, conversationType, targetId, title, fixedMsgSentTime);
                    } else {
                        Toast.makeText(this, "该功能只支持vip用户", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "该功能只支持vip用户", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_follow_closely:
//                关注
                addorDeleteFocused();
                break;
            case R.id.ll_type1:
                commitAllowingStateLoss(0);
                setTextColor(0);
                break;
            case R.id.ll_type2:
                commitAllowingStateLoss(1);
                setTextColor(1);
                break;
            case R.id.ll_type3:
                commitAllowingStateLoss(2);
                setTextColor(2);
                break;
            case R.id.ll_type4:
                commitAllowingStateLoss(3);
                setTextColor(3);
                break;
        }

    }


    private void rewardDialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_reward, null);
        dialog.setContentView(view);

        EditText et_money = view.findViewById(R.id.et_money);
//        moneyLimit(et_money);

        TextView tv_over = view.findViewById(R.id.tv_over);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        if (StringUt.isEmpty(over)) {
            tv_over.setText("￥0");
        } else {
            tv_over.setText("￥" + over);
        }

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(et_money.getText().toString().trim()) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(et_money.getText().toString().trim())) {
                        //钱够支付
                        dialogPass(et_money.getText().toString().trim());
                        dialog.dismiss();
                    } else {
                        Toast.makeText(OthersHomepageAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                    }
                } else if (StringUt.isEmpty(over)) {
                    Toast.makeText(OthersHomepageAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }


    private void dialogPass(String money) {
        final PayPassDialog dialog = new PayPassDialog(OthersHomepageAc.this);
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        RewardByWallet(passContent, money, dialog);
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }


    private void RewardByWallet(String passContent, String money, PayPassDialog dialog) {
        RewardByWalletBody rewardByWalletBody = new RewardByWalletBody();
//        rewardByWalletBody.setDynamicId(id);
        rewardByWalletBody.setUid((String) SPUtil.get(this, Constants.SP_ID, ""));
        rewardByWalletBody.setToUid(uid);
        rewardByWalletBody.setMoney(money);
        rewardByWalletBody.setPassWord(passContent);
        ApiUtil.getHomeApi().RewardByWallet(SPUtil.getToken(this),
                rewardByWalletBody).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                dialog.dismiss();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            Toast.makeText(OthersHomepageAc.this, "打赏成功", Toast.LENGTH_SHORT).show();
                            queryById2();
                        } else {
                            Toast.makeText(OthersHomepageAc.this, data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    /**
     * 关注
     */
    private void addorDeleteFocused() {
        DeleteFocusedBean deleteFocusedBean = new DeleteFocusedBean();
        deleteFocusedBean.setUid(uid);
        ApiUtil.getUserApi().addorDeleteFocused(SPUtil.getToken(OthersHomepageAc.this),
                deleteFocusedBean).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            queryById();
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }

            }
        }));
    }

    public void setTextColor(int position) {
        for (int i = 0; i < mTextViewList.size(); i++) {
            if (position == i) {
                mTextViewList.get(position).setTextColor(getResources().getColor(R.color.hot_pink));
                mViewList.get(position).setVisibility(View.VISIBLE);
            } else {
                mTextViewList.get(i).setTextColor(getResources().getColor(R.color.black));
                mViewList.get(i).setVisibility(View.INVISIBLE);
            }
        }
    }
}
